<template>
  <div style="padding: 10px 20px;background-color: #ffffff">
    <el-link type="primary" @click="barkList">返回列表</el-link>
  </div>
  <FormCreate :rule="rule.data" :option="options" v-model="formData" v-model:api="fApi"></FormCreate>
  <div style="margin-left: 126px;margin-top: 30px;display: flex;align-items: center">
    <div v-if="!editTow">
      <el-button type="success" @click="submit('1')">存草稿</el-button>
      <el-button type="primary" @click="submit('0')">提交</el-button>
    </div>
    <div v-else>
      <el-button type="primary" @click="submit()">保存</el-button>
    </div>
    <el-button style="margin-left: 10px" type="info" @click="cancel">取消</el-button>
  </div>
</template>

<script setup>
import { debounce, throttle } from 'lodash'
import {useRoute,useRouter} from "vue-router";
import {
  _addPerson,
  _getFormInfoById,
  _getOptionListByName,
  _getPersonId,
  _idCodeSearch,
  _updatePerson
} from "../../http/api.js";
import {ElLoading, ElMessage} from "element-plus";
import formCreate from "@form-create/element-ui";
import {ref,reactive} from "vue";
// import Validator from 'validator';
import {addField} from "../../utils/field.js";


const route = useRoute();
const router = useRouter();

const loginId = sessionStorage.getItem('loginId');
const exhibitionId = sessionStorage.getItem('projectId');
if(!loginId||!exhibitionId) {
  ElMessage({message: '操作异常', type: 'error' });
  localStorage.clear();
  sessionStorage.clear();
  router.replace({ path: '/'})
}
const templateId = route.query.templateId; // 模板id
const personId = route.query.personId; // 数据id
const type = route.query.type; // 证件类型标志
const editTow = route.query.editTow; // 是否二审修改
if(!templateId ||!type) {
  ElMessage({message: '操作异常', type: 'error' });
  localStorage.clear();
  sessionStorage.clear();
  router.replace({ path: '/'})
}
const registrationId = ref(''); // 保留注册id
//获取 formCreate 组件
const FormCreate = formCreate.$form();
const fApi = ref({});
const formData = ref({});
const options = ref({
  //表单提交事件
  submitBtn: false,
  form:{
    labelWidth: '280px'
  }
});
// 选择的字段
const rule = reactive({
  data:[]
})
// 返回列表
const barkList = () => {
  router.go(-1)
}
// 获取模板字段详情
const getInfoById = () => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
  _getFormInfoById(templateId)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let item = res.data.data;
          let fieldTemplateList = item.fieldTemplateList;
          let types = [];
          for (let i = 0; i < fieldTemplateList.length; i++) {
            let item = fieldTemplateList[i];
            if(item.fieldType === 'select' || item.fieldType === 'radio') {
              types.push(item.fieldName)
            }
          }
          getOptionListByName(types.toString(),fieldTemplateList)
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常', type: 'error' });
      })
}
if(templateId) {
  getInfoById()
}
// 获取字段列表二级选项
const getOptionListByName = (typeString,list) => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
  _getOptionListByName(typeString)
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          let arr = res.data.data;
          console.log(arr);
          for (let j = 0; j < arr.length; j++) {
            for (let i = 0; i < list.length; i++) {
              if(arr[j].fieldType === list[i].fieldName) {
                let listData = arr[j].list||[];
                let arrList = [];
                listData.forEach(v => {
                  arrList.push({ label: type == 2 ?v.nameEn:v.name,value: v.value })
                })
                list[i]['optionsData'] = arrList;
              }
            }
          }
          list.forEach(v => {
            let config = addField(v.fieldType,{field:v.fieldName,title:v.notes},v.optionsData);
            config.effect.required = (v.isFlag === '0');
            rule.data.push(config)
          })
          fApi.value.refreshOptions();
          console.log(rule.data);
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
        ElMessage({message: '网络异常', type: 'error' });
      })
}

// 获取数据详情
const getPersonId = () => {
  _getPersonId(personId)
      .then(res => {
        console.log(res);
        if(res.data.ok) {
          let item = res.data.data.value;
          let address1 = [];
          let address2 = [];
          let address3 = [];
          let address4 = [];
          let address5 = [];
          let address6 = [];
          let address7 = [];
          let address8 = [];
          let address9 = [];
          let address10 = [];
          if(item.address1) {
            address1 = item.address1.split('-');
            item['address1'] = address1;
          }
          if(item.address2) {
            address2 = item.address2.split('-');
            item['address2'] = address2;
          }
          if(item.address3) {
            address3 = item.address3.split('-');
            item['address3'] = address3;
          }
          if(item.address4) {
            address4 = item.address4.split('-');
            item['address4'] = address4;
          }
          if(item.address5) {
            address5 = item.address5.split('-');
            item['address5'] = address5;
          }
          if(item.address6) {
            address6 = item.address6.split('-');
            item['address6'] = address6;
          }
          if(item.address7) {
            address7 = item.address7.split('-');
            item['address7'] = address7;
          }
          if(item.address8) {
            address8 = item.address8.split('-');
            item['address8'] = address8;
          }
          if(item.address9) {
            address9 = item.address9.split('-');
            item['address9'] = address9;
          }
          if(item.address10) {
            address10 = item.address10.split('-');
            item['address10'] = address10;
          }

          if(item.cardTypeOne) {
            item['cardTypeOneA'] = item.cardTypeOne;
          }
          if(item.cardTypeTwo) {
            item['cardTypeTwoA'] = item.cardTypeTwo;
          }
          console.log(item);
          if(item.registrationId) {
            registrationId.value = item.registrationId;
          }
          fApi.value.coverValue({ ... item });
        }
      })
      .catch(err => {
        console.log(err);
      })
}
if(personId) {
  getPersonId()
}

// 提交数据
const submit = debounce((state) => {
  fApi.value.submit((formData) => {
    let idCode = formData.idCode||'';
    let passportNumber = formData.passportNumber||'';
    let passportNationality = formData.passportNationality||'';
    let type = idCode ? '0':'1'; // 0境内 1境外
    // let isPass = Validator.isIdentityCard(idCode, 'any');
    // if(idCode) {
    //   if(idCode.length !== 18 || !isPass) {
    //     return ElMessage({message: '证件号码有误', type: 'warning' });
    //   }
    // }
    // if(passportNumber) {
    //   if(passportNumber.length < 6) return ElMessage({message: '证件号码有误', type: 'warning' });
    // }

    let address1 = formData.address1||'';
    let address2 = formData.address2||'';
    let address3 = formData.address3||'';
    let address4 = formData.address4||'';
    let address5 = formData.address5||'';
    let address6 = formData.address6||'';
    let address7 = formData.address7||'';
    let address8 = formData.address8||'';
    let address9 = formData.address9||'';
    let address10 = formData.address10||'';
    if(address1) formData.address1 = address1.toString().replaceAll(',','-');
    if(address2) formData.address2 = address2.toString().replaceAll(',','-');
    if(address3) formData.address3 = address3.toString().replaceAll(',','-');
    if(address4) formData.address4 = address4.toString().replaceAll(',','-');
    if(address5) formData.address5 = address5.toString().replaceAll(',','-');
    if(address6) formData.address6 = address6.toString().replaceAll(',','-');
    if(address7) formData.address7 = address7.toString().replaceAll(',','-');
    if(address8) formData.address8 = address8.toString().replaceAll(',','-');
    if(address9) formData.address9 = address9.toString().replaceAll(',','-');
    if(address10) formData.address10 = address10.toString();
    if(registrationId.value) {
      formData['registrationId'] = registrationId.value;
    }
    console.log(formData);
    let params = {
      value: JSON.stringify(formData),
      // json:formData,
      templateId,
      state,
      userId: loginId,
      exhibitionId: exhibitionId,
      type
      // oneLevelState: 0,
      // twoLevelState: 0,
      // threeLevel: 0,
    }
    if(!state) {
      delete params.state;
    }
    console.log(params);
    if(personId) {
      const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)',})
      params['id'] = personId;
      delete params.userId;
      delete params.exhibitionId;
      _updatePerson(params)
          .then(res => {
            console.log(res);
            loading.close();
            if(res.data.ok) {
              ElMessage({message: '更新成功', type: 'success' });
              router.go(-1)
            }else{
              ElMessage({message: res.data.msg, type: 'error' });
            }
          })
          .catch(err => {
            console.log(err);
            loading.close();
            ElMessage({message: '网络异常，请重试', type: 'error' });
          })
    }else {
      if(idCode || (passportNumber && passportNationality)) {
        idCodeSearch(idCode||passportNumber,type,passportNationality,params)
      }else {
        const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
        _addPerson(params)
            .then(res => {
              console.log(res);
              loading.close();
              if(res.data.ok) {
                ElMessage({message: '添加成功', type: 'success' });
                router.go(-1)
              }else{
                ElMessage({message: res.data.msg, type: 'error' });
              }
            })
            .catch(err => {
              console.log(err);
              loading.close();
              ElMessage({message: '网络异常，请重试', type: 'error' });
            })
      }
    }
  })
},1000)
// 身份证号码查重
const idCodeSearch = (idCode,type,passportNationality,params) => {
  const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
  _idCodeSearch(idCode,type,passportNationality||'passportNationality')
      .then(res => {
        console.log(res);
        loading.close();
        if(res.data.ok) {
          const loading = ElLoading.service({lock: true, text: 'Loading', background: 'rgba(0, 0, 0, 0.7)'})
          _addPerson(params)
              .then(res => {
                console.log(res);
                loading.close();
                if(res.data.ok) {
                  ElMessage({message: '添加成功', type: 'success' });
                  router.go(-1)
                }else{
                  ElMessage({message: res.data.msg, type: 'error' });
                }
              })
              .catch(err => {
                console.log(err);
                loading.close();
                ElMessage({message: '网络异常，请重试', type: 'error' });
              })
        }else{
          ElMessage({message: res.data.msg, type: 'warning' });
        }
      })
      .catch(err => {
        console.log(err);
        loading.close();
      })

}
// 取消
const cancel = () => {
  router.go(-1)
}
</script>

<style scoped lang="scss">

</style>